package com.hdw.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.hdw.common.constant.CommonConstant;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

public class TokenUtil {
    //私钥
    public static final String SECRET = "Axmk89Li3Aji9M";
    /**
     * token的有效时间,不需要自己验证失效,当失效后,会自动抛出异常
     */
    public static final Long expTime = 60 * 30 * 1000L;

    private static final String CURRENT_TIME = "currentTime";
    private static final String SD_SOFT = "sdSoft";
    private static final String USERNAME = "username";

    /**
     * 创建一个token
     * @param id
     * @return
     */
    public static String getToken(String username,Long currentTime,String sdSoft) {
        String token="";
        Date expiresDate = new Date(System.currentTimeMillis()+expTime);
        token= JWT.create().withAudience(username)
                .withExpiresAt(expiresDate)
                .withClaim(CURRENT_TIME,currentTime)
                .withClaim(SD_SOFT,sdSoft)
                .withClaim(USERNAME,username)
                .sign(Algorithm.HMAC256(SECRET));
        return token;
    }

    public static String getClaim(String token,String cliaimName) {
        DecodedJWT jwt;
        try {
            jwt = JWT.decode(token);
        } catch (Exception e) {
            return null;
        }
        if (new Date().getTime() > jwt.getExpiresAt().getTime()) {
            return null;
        }
        return jwt.getClaim(cliaimName).asString();
    }

    public static boolean verifyToken(String token, ServletResponse response){
        try{
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            verifier.verify(token);
            Long tokenTime = Long.parseLong(getClaim(token,getClaim(token,CURRENT_TIME)));
            String username = getClaim(token,getClaim(token,USERNAME));
            //RedisTemplateConfig redisTemplateConfig = SpringBeanUtil.getBean(RedisTemplateConfig.class);
            Long createTime = null;//Long.parseLong(redisTemplateConfig.get(CommonConstant.REDIS_PREF_USERNAME+username).toString());
            if(tokenTime==createTime) {
                String sdSoft = getClaim(token,getClaim(token,SD_SOFT));
                String newToken = getToken(username,tokenTime,sdSoft);
                HttpServletResponse httpServletResponse = (HttpServletResponse) response;
                httpServletResponse.setHeader(CommonConstant.X_ACCESS_TOKEN, newToken);
                return true;
            } else {
                return false;
            }
        }catch(Exception e){
            return false;
        }
    }
}
